<script setup lang="ts">
// 导入所需的依赖
import { useMemberStore } from '@/stores'
import type { goodsListItem } from '@/types/goods'
import { ref, reactive, onMounted } from 'vue'
import { fullUrl, checkImage } from '@/utils/common'
import { getShareInfoApi } from '@/api/goods'
import { getShareUrl } from './sharePoster'

// 定义组件属性
const props = defineProps<{
  goods: goodsListItem
}>()

// 定义响应式引用
const sharePosterRef = ref()
const painter = ref()

// 定义响应式状态对象
const state = reactive({
  posterImgPath: '', // 海报图片路径
  showPoster: false, // 是否显示海报
  userAvatarImg: '', // 用户头像图片
  qrcodeUrl: '', // 二维码URL
  isGenerating: false // 是否正在生成海报
})

// 组件挂载时预加载用户头像
onMounted(async () => {
  const memberStore = useMemberStore()
  if (memberStore.profile?.avatar) {
    try {
      const validImageUrl = await checkImage(fullUrl(memberStore.profile.avatar))
      state.userAvatarImg = validImageUrl
    } catch (error) {
      console.log('Failed to preload avatar:', error)
      state.userAvatarImg = '/static/images/default_avatar.png'
    }
  } else {
    state.userAvatarImg = '/static/images/default_avatar.png'
  }
})

// 打开海报生成弹窗
const open = async () => {
  if (state.isGenerating) return

  state.isGenerating = true
  state.posterImgPath = ''
  
  // 如果头像未加载，则加载头像
  if (!state.userAvatarImg) {
    try {
      const validImageUrl = await checkImage(fullUrl(useMemberStore().profile?.avatar || ''))
      state.userAvatarImg = validImageUrl
    } catch (error) {
      state.userAvatarImg = '/static/images/default_avatar.png'
    }
  }

  // 获取微信小程序的二维码
  // #ifdef MP-WEIXIN
  try {
    const shareInfo = await getShareInfoApi(props.goods.id)
    state.qrcodeUrl = shareInfo.result.qrcode_url
  } catch (error) {
    console.error('Failed to get QR code:', error)
    uni.showToast({
      title: 'Failed to generate QR code',
      icon: 'none'
    })
  }
  // #endif

  // 打开弹窗
  try {
    await sharePosterRef.value?.open()
    state.showPoster = true

    await uni.showLoading({
      title: 'Generating poster...',
      mask: true,
    })
  } catch (error) {
    console.error('Error opening poster popup:', error)
    state.isGenerating = false
    uni.hideLoading()
    uni.showToast({
      title: 'Failed to generate poster',
      icon: 'none'
    })
  }
}

// 关闭海报生成弹窗
const close = () => {
  try {
    sharePosterRef.value?.close()
    state.showPoster = false
    state.isGenerating = false
    // 关闭后清除海报图片路径以释放内存
    setTimeout(() => {
      state.posterImgPath = ''
    }, 300)
  } catch (error) {
    console.error('Error closing poster popup:', error)
  }
}

// 画布绘制完成时的回调
const onDone = () => {
  console.log('Poster canvas drawing completed')
}

// 海报生成成功时的回调
const onSuccess = (imgPath: string) => {
  try {
    setTimeout(() => {
      state.posterImgPath = imgPath
      state.isGenerating = false
      uni.hideLoading()
    }, 500)
  } catch (error) {
    console.error('Error in poster success callback:', error)
    state.isGenerating = false
    uni.hideLoading()
    uni.showToast({
      title: 'Failed to generate poster',
      icon: 'none'
    })
  }
}

// 处理海报生成过程中的错误
const onError = (error: any) => {
  console.error('Poster generation error:', error)
  state.isGenerating = false
  uni.hideLoading()
  uni.showToast({
    title: 'Failed to generate poster',
    icon: 'none'
  })
}

// 保存海报到相册
const onSave = () => {
  if (!state.posterImgPath) {
    return uni.showToast({
      title: 'Poster not generated yet',
      icon: 'none'
    })
  }
  
  // 微信小程序环境
  // #ifdef MP-WEIXIN
  try {
    painter.value.canvasToTempFilePathSync({
      fileType: 'jpg',
      pathType: 'url',
      quality: 1,
      success: (res: any) => {
        uni.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: () => {
            uni.showToast({
              title: 'Save successful',
              icon: 'success',
            })
            // 延迟关闭海报
            setTimeout(() => {
              close()
            }, 1500)
          },
          fail: (err: any) => {
            console.log('Save error:', err)
            if (err.errMsg.includes('cancel')) {
              uni.showToast({
                title: 'Save canceled',
                icon: 'none',
              })
            } else if (err.errMsg.includes('auth')) {
              uni.showModal({
                title: 'Permission Required',
                content: 'Please allow access to your photo album to save the image',
                success: (res) => {
                  if (res.confirm) {
                    uni.openSetting()
                  }
                }
              })
            } else {
              uni.showToast({
                title: 'Save failed',
                icon: 'none',
              })
            }
          }
        })
      },
      fail: (err: any) => {
        console.error('Failed to convert canvas to image:', err)
        uni.showToast({
          title: 'Failed to generate image',
          icon: 'none'
        })
      }
    })
  } catch (error) {
    console.error('Error saving poster:', error)
    uni.showToast({
      title: 'Save failed',
      icon: 'none'
    })
  }
  // #endif
  
  // H5环境
  // #ifdef H5
  // 显示长按图片保存的提示
  uni.showToast({
    title: 'Long press the image to save',
    icon: 'none',
    duration: 2000
  })
  // #endif
}

// 暴露组件方法
defineExpose({ sharePosterRef, open, close })
</script>

<template>
  <uni-popup ref="sharePosterRef" type="center" :animation="false" :mask-click="false">
    <view class="poster-container">
      <!-- 海报图片 -->
      <image v-if="state.posterImgPath" :src="state.posterImgPath" mode="widthFix" class="poster-image" />
      <!-- 生成中的占位符 -->
      <view v-if="!state.posterImgPath && state.showPoster" class="generating-placeholder">
        <text>Generating poster...</text>
      </view>
      
      <view v-if="state.showPoster">
        <view class="poster">
          <!-- 海报画布 -->
          <l-painter
            ref="painter"
            isCanvasToTempFilePath
            @success="onSuccess"
            @error="onError"
            css="width: 750rpx; padding-bottom: 40rpx; background: #edca88;"
            hidden
            @done="onDone"
            :after-delay="500"
          >
            <!-- 用户头像 -->
            <l-painter-image
              :src="state.userAvatarImg"
              css="margin-left: 40rpx; margin-top: 40rpx; width: 100rpx; height: 100rpx; border-radius: 50%;"
            />
            
            <!-- 用户信息 -->
            <l-painter-view css="margin-top: 40rpx; padding-left: 20rpx; display: inline-block">
              <l-painter-text
                :text="useMemberStore().profile?.nickname || 'User'"
                css="display: block; padding-bottom: 20rpx; color: #000; font-size: 32rpx; fontWeight: bold"
              />
              <l-painter-text text="I recommend a good product to you" css="color: #000; font-size: 24rpx" />
            </l-painter-view>
            
            <!-- 商品卡片 -->
            <l-painter-view
              css="margin-left: 40rpx; margin-top: 30rpx; padding: 32rpx; box-sizing: border-box; background: #fff; border-radius: 16rpx; width: 670rpx; box-shadow: 0 20rpx 58rpx rgba(0,0,0,.15)"
            >
              <!-- 商品图片 -->
              <l-painter-image
                :src="fullUrl(props.goods.images?.[0] || '')"
                css="object-fit: cover; object-position: 50% 50%; width: 600rpx; height: 500rpx; border-radius: 12rpx;"
              />
              
              <!-- Price -->
              <l-painter-view
                css="margin-top: 32rpx; color: #FF0000; font-weight: bold; font-size: 28rpx; line-height: 1em;"
              >
                <l-painter-text text="$" css="vertical-align: bottom" />
                <l-painter-text
                  :text="props.goods.min_price ? props.goods.min_price.toString().split('.')[0] : '0'"
                  css="vertical-align: bottom; font-size: 58rpx"
                />
                <l-painter-text
                  :text="props.goods.min_price ? `.${props.goods.min_price.toString().split('.')[1] || '00'}` : '.00'"
                  css="vertical-align: bottom"
                />
                <l-painter-text
                  :text="`$${props.goods.max_origin_price || 0}`"
                  css="vertical-align: bottom; padding-left: 10rpx; font-weight: normal; text-decoration: line-through; color: #999999"
                />
              </l-painter-view>
              
              <!-- Product Name -->
              <l-painter-view css="margin-top: 30rpx">
                <l-painter-text
                  :text="props.goods.name || 'Product'"
                  css="line-clamp: 2; color: #333333; line-height: 1.5em; width: 620rpx; font-size: 30rpx; padding-right:32rpx; box-sizing: border-box"
                ></l-painter-text>
              </l-painter-view>
              
              <!-- QR Code Section -->
              <l-painter-view css="margin-top: 30rpx; display: flex; flex-wrap: nowrap;">
                <l-painter-text
                  text="Long press or scan the QR code to view details"
                  css="float: left; padding-bottom: 10rpx; color: #999999; font-size: 26rpx; margin-top: 60rpx; margin-right: 160rpx"
                />
                <!-- WeChat QR Code -->
                <!-- #ifdef MP-WEIXIN -->
                <l-painter-image
                  v-if="state.qrcodeUrl"
                  :src="state.qrcodeUrl"
                  css="float: right; width: 150rpx; height: 150rpx;"
                />
                <!-- #endif -->
                
                <!-- Generated QR Code for Web -->
                <!-- #ifdef H5 -->
                <l-painter-qrcode
                  :text="getShareUrl(props.goods.id)"
                  css="float: right; width: 150rpx; height: 150rpx;"
                />
                <!-- #endif -->
              </l-painter-view>
            </l-painter-view>
          </l-painter>
        </view>
        
        <!-- Action Buttons -->
        <view class="action" v-if="state.posterImgPath">
          <view class="button cancel" @tap="close()">Cancel</view>
          
          <!-- Web: Show instruction -->
          <!-- #ifdef H5 -->
          <view class="save-tip">Long press the image to save</view>
          <!-- #endif -->
          
          <!-- WeChat: Save button -->
          <!-- #ifdef MP-WEIXIN -->
          <view class="button save" @tap="onSave()">Save to Album</view>
          <!-- #endif -->
        </view>
      </view>
    </view>
  </uni-popup>
</template>

<style lang="scss" scoped>
.poster-container {
  width: 700rpx;
  border-radius: 16rpx;
  overflow: hidden;
  background-color: #fff;
}

.poster-image {
  width: 700rpx;
  display: block;
}

.generating-placeholder {
  width: 700rpx;
  height: 300rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
  
  text {
    font-size: 28rpx;
    color: #666;
  }
}

.action {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx;
  background: #f5f5f5;

  .button {
    padding: 16rpx 32rpx;
    margin: 0 10rpx;
    background: #ff784d;
    color: #ffffff;
    display: inline-block;
    text-align: center;
    border-radius: 40rpx;
    font-size: 28rpx;

    &:active {
      opacity: 0.8;
    }
  }

  .cancel {
    background: #b3b3b3;
    color: #ffffff;
  }
  
  .save {
    background: #ff5f3c;
  }
  
  .save-tip {
    font-size: 28rpx;
    color: #666;
  }
}
</style>
